package com.sunbird.crm.base.configurate.shiro;

import com.sunbird.crm.entity.sys.TUser;

import com.sunbird.crm.servce.SysRoleService;
import com.sunbird.crm.servce.SysUserService;
import com.sunbird.crm.servce.impl.SysPerssionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @ClassName MyShiroRealm 自定义realm
 * @Descriptiom TODO
 * @Author Sunbird
 * @Date 2019/8/16 21:16
 * @Version 1.0
 **/
public class MyShiroRealm  extends AuthorizingRealm {

    private  Logger LOGGER = LoggerFactory.getLogger(MyShiroRealm.class);

    @Autowired
    private SysRoleService roleService;

//    @Autowired
//    private SysPerssionService perssionService;

    @Autowired
    private SysUserService sysUserService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到用户名
       Object primaryPrincipal  =  principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (primaryPrincipal instanceof  TUser){
    LOGGER.debug("-------- 获取用户角色 -----------");
            TUser user = (TUser) primaryPrincipal;
//            /* 查询角色名称 */
            Set<String> roles =roleService.findRoleNameByUserId(user.getUserCode());
//            authorizationInfo.addRoles(roles);
//            /*根据角色查询权限*/
//            roleService.findRoleNameByUserId(user.getUserCode());
////            Set<String> permissions = sysUserService.findPermissionsByUserRoleId(role.getRoleid());
              authorizationInfo.addStringPermissions(roles);
        }
        return authorizationInfo;
//        return  null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            //1： 从主体传过来的token认证信息
        LOGGER.debug("进行身份认证");
        UsernamePasswordToken token  =(UsernamePasswordToken) authenticationToken;
        String name = token.getUsername();
        String password =String.valueOf(token.getPassword());
        TUser user =new TUser();
        user.setUserCode(name);
        user.setPassword(password);
        //从数据库获取对应的用户名和密码
        TUser userList = sysUserService.getUser(user);
        if (userList != null){
            //用户状态为禁用状态
            if (!userList.getStatus().equals("0") ){
                throw  new DisabledAccountException(" 该账户不可用 ");
            }
            LOGGER.debug("------------Shiro 认证成功 --------------- ");
            SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(userList,userList.getPassword(),getName());
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("user",userList);
            return (AuthenticationInfo)authorizationInfo;
        }
        throw  new UnknownAccountException("没有该账户");
    }

    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo()
    {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
